package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.*;

import java.util.List;

/**
 * 组合多个 Future 示例
 *
 * @author yangyunjiao
 */
public class MultipleFuturesExample {
    public static void main(String[] args) throws Exception {
        SettableFuture<String> future1 = SettableFuture.create();
        SettableFuture<String> future2 = SettableFuture.create();
        SettableFuture<String> future3 = SettableFuture.create();

        // 组合所有 future
        ListenableFuture<List<String>> allFutures =
                Futures.allAsList(future1, future2, future3);

        // 设置回调
        Futures.addCallback(allFutures, new FutureCallback<List<String>>() {
            @Override
            public void onSuccess(List<String> results) {
                System.out.println("所有任务完成: " + results);
            }

            @Override
            public void onFailure(Throwable throwable) {
                System.out.println("有任务失败: " + throwable.getMessage());
            }
        }, MoreExecutors.directExecutor());

        // 分别设置结果
        new Thread(() -> {
            future1.set("结果1");
            future2.set("结果2");
            future3.set("结果3");
        }).start();

        Thread.sleep(2000);
    }
}
